%% Copyright (C) 2007, Lucas Carlson
%% File    : utils.erl
%% Author  : Lucas Carlson (lucas@rufy.com)

-module(utils).
-export([config/1, unix_time/0, delete_all/2, index/2]).

config(Fname) ->
    case file:read_file(Fname) of
	{ok, Bin} ->
		{ok, Lines} = regexp:split(binary_to_list(Bin), "\n"),
	    scan_file(Lines, dict:new());
	{error, Reason} ->
	    {error, Reason}
    end.

scan_file([Line | RestOfLines], Config) ->
	case config_key(Line) of
		[] -> scan_file(RestOfLines, Config);
		Key -> 
			scan_file(RestOfLines, dict:store(list_to_atom(Key), config_value(Line), Config))
	end;
scan_file([], Config) ->
	Config.

config_key(Line) ->
	{ok, [Key|_]} = regexp:split(Line, ":"),
	Key.

config_value(Line) ->
	{ok, [_|Values]} = regexp:split(Line, ":"),
	case lists:append(lists:map(fun(V) -> V ++ ":" end, Values)) of
		[] ->
			[];
		TmpValue ->
			case string:strip(lists:sublist(TmpValue, 1, length(TmpValue) - 1)) of
				[$[ | Value] ->
					{ok, NewValue} = regexp:split(lists:sublist(Value, 1, length(Value)-1), ","),
					lists:map(fun(V2) -> list_to_atom(string:strip(V2)) end, NewValue);
				Value ->
					case regexp:match(Value, "^[0-9]+$") of
						{match, _, _} ->
							list_to_integer(Value);
						nomatch ->
							list_to_atom(Value)
					end
			end
	end.

unix_time() ->
    calendar:datetime_to_gregorian_seconds({date(), time()}) -
        calendar:datetime_to_gregorian_seconds({{1970,1,1},{0,0,0}}).
delete_all(_, []) -> 
    [];
delete_all(H, [H|T]) -> 
    delete_all(H, T);
delete_all(X, [H|T]) -> 
    [H|delete_all(X, T)].

index(X, [X,_]) ->
	{ok, 1};
index(X, A) ->
	Index = lists:foldl(fun(V, {T, C}) ->
		case C == no of
			true ->
				case V == X of
					true -> {T, yes};
					false -> {T + 1, no}
				end;
			false ->
				{T, C}
		end
	end, {1, no}, A),
	case Index of
		{I, yes} ->
			{ok, I};
		{_, no} ->
			no
	end.